package com.oauth.google.client.ui.tabs;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.oauth.components.client.rpc.OAuthAsnyCallBack;
import com.oauth.google.client.beans.orkut.HttpQueryString;
import com.oauth.google.client.beans.youtube.GoogleYouTubeModel;
import com.oauth.google.client.rpc.youtube.YouTubeRemoteService;
import com.oauth.google.client.rpc.youtube.YouTubeRemoteServiceAsync;
import com.oauth.google.client.ui.HasTabs;
import com.oauth.google.client.ui.youtube.HomePanel;
import com.oauth.google.client.ui.youtube.LoginPanel;

public class GoogleYouTubePanel extends Composite implements HasTabs {

	private static GoogleYouTubePanelUiBinder uiBinder = GWT
			.create(GoogleYouTubePanelUiBinder.class);

	protected final YouTubeRemoteServiceAsync googleService = GWT
			.create(YouTubeRemoteService.class);

	interface GoogleYouTubePanelUiBinder extends
			UiBinder<FlowPanel, GoogleYouTubePanel> {
	}

	@UiField
	HorizontalPanel staticPanel;

	@UiField
	DeckPanel deckPanel;

	@UiField
	Anchor viewAllLink;

	@UiField
	HomePanel homePanel;

	@UiField
	LoginPanel loginPanel;

	@UiField
	Image logo;

	public GoogleYouTubePanel() {
		initWidget(uiBinder.createAndBindUi(this));
		loginPanel.setService(googleService);
		staticPanel.setCellHorizontalAlignment(logo, VerticalPanel.ALIGN_LEFT);
		staticPanel.setCellHorizontalAlignment(viewAllLink,
				VerticalPanel.ALIGN_RIGHT);
	}

	public void init() {
		deckPanel.showWidget(0);
		String queryString = Window.Location.getQueryString();
		HttpQueryString youtubeQueryString = new HttpQueryString(queryString);

		googleService.getYouTubeVideos(youtubeQueryString,
				new OAuthAsnyCallBack<GoogleYouTubeModel>() {
					public void onSuccess(GoogleYouTubeModel pModel) {

						if (pModel != null) {
							if (pModel.isLoginView()) {
								deckPanel.showWidget(1);
							} else {
								deckPanel.showWidget(2);
								homePanel.setData(pModel);
							}
						}
					}
				});
	}

	@UiHandler("viewAllLink")
	public void onClick(ClickEvent pEvent) {
		Window.open("http://www.youtube.com", "YouTube", null);
	}

}